package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.LocationBean;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DemoUtils;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.geolocation.TencentPoi;
import com.tencent.mapsdk.raster.model.BitmapDescriptorFactory;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.mapsdk.raster.model.Marker;
import com.tencent.mapsdk.raster.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.map.MapActivity;
import com.tencent.tencentmap.mapsdk.map.MapView;
import com.tencent.tencentmap.mapsdk.map.TencentMap;
import com.tencent.tencentmap.mapsdk.map.UiSettings;

import java.util.List;


/**
 * 作者：Administrator on 2017/6/22 15:38
 * 邮箱：zhanghuaiha@gmail.com
 */

public class TencentMapActivity extends MapActivity implements TencentLocationListener {
    private MapView mapview;
    private TencentMap map;
    private int mLevel = 2;
    private TencentLocationManager mLocationManager;
    private ImageView map_back;
    private TextView map_save;
    private Marker marker;
    private static final int LAT_LOG = 5;// 经纬度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        mapview = (MapView) findViewById(R.id.mapview);
        map_back = (ImageView) findViewById(R.id.map_back);
        map_save = (TextView) findViewById(R.id.map_save);
        map_back.setOnClickListener(v -> finish());
        map_save.setOnClickListener(v -> {
            Intent intent = new Intent();
            LatLng position = marker.getPosition();
            Log.e("logcation","维度："+position.getLatitude()+"!!精度："+position.getLongitude());
            intent.putExtra("lat",position.getLatitude());
            intent.putExtra("log",position.getLongitude());
            setResult(LAT_LOG,intent);
            finish();
        });


        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            if(checkSelfPermission(permissions[0]) == PackageManager.PERMISSION_DENIED){
                requestPermissions(permissions, 0);
            }
        }

        mLocationManager = TencentLocationManager.getInstance(this);
        // 设置坐标系为 gcj-02, 缺省坐标为 gcj-02, 所以通常不必进行如下调用
       // mLocationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        startLocation();
    }

    private void ininData(LocationBean locationBean) {
        map = mapview.getMap();
        map.setCenter(new LatLng(locationBean.getLat(),locationBean.getLog()));
        map.setZoom(15);

        //获取UiSettings实例
        UiSettings uiSettings = mapview.getUiSettings();
        //设置logo到屏幕底部中心
        uiSettings.setLogoPosition(UiSettings.LOGO_POSITION_CENTER_BOTTOM);
        //设置比例尺到屏幕右下角
        uiSettings.setScaleViewPosition(UiSettings.SCALEVIEW_POSITION_RIGHT_BOTTOM);


        marker = mapview.addMarker(new MarkerOptions()
                .position(new LatLng(locationBean.getLat(),locationBean.getLog()))
                .title("长按拖动图标选择位置")
                .anchor(0.5f, 0.5f)
                .draggable(false) //不允许拖拽
                .icon(BitmapDescriptorFactory
                        .defaultMarker())
                .draggable(true));
                marker.showInfoWindow();// 设置默认显示一个infoWindow

    }



    // 响应点击"开始"
    public void startLocation() {
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest.create()
                .setInterval(5000) // 设置定位周期
                .setAllowGPS(true)  //当为false时，设置不启动GPS。默认启动
                .setAllowIndoorLocation(true)  //设置启动室内定位，默认不启动
                .setQQ("10001")
                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA); // 设置定位level

        // 开始定位
        mLocationManager.requestLocationUpdates(request, this);

        Log.e("mappp", DemoUtils.toString(mLocationManager.getCoordinateType()));
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationManager.removeUpdates(this);
    }



    @Override
    public void onLocationChanged(TencentLocation location, int error, String s) {
        LocationBean locationBean = null;
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            locationBean = toString(location, TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        } else {
            // 定位失败
            String msg = "定位失败: " + s;
            locationBean = new LocationBean();
            locationBean.setName(msg);
        }
        updateLocationStatus(locationBean);
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    // ====== location callback

    private void updateLocationStatus(LocationBean locationBean) {
        mLocationManager.removeUpdates(this);
        ininData(locationBean);
        Log.e("map",locationBean.getName());

    }


    // ===== util method
    private static LocationBean toString(TencentLocation location, int level) {
        StringBuilder sb = new StringBuilder();
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
            LocationBean locationBean = new LocationBean();
            locationBean.setLat(location.getLatitude());
            locationBean.setLog(location.getLongitude());
            locationBean.setName("获取定位成功");
            return locationBean;
        }

        sb.append("latitude=").append(location.getLatitude()).append(",");
        sb.append("longitude=").append(location.getLongitude()).append(",");
        sb.append("altitude=").append(location.getAltitude()).append(",");
        sb.append("accuracy=").append(location.getAccuracy()).append(",");
        sb.append("indoorBuildingId=").append(location.getIndoorBuildingId()).append(",");
        sb.append("indoorBuildingFloor=").append(location.getIndoorBuildingFloor()).append(",");

        switch (level) {
            case TencentLocationRequest.REQUEST_LEVEL_GEO:
                break;

            case TencentLocationRequest.REQUEST_LEVEL_NAME:
                sb.append("name=").append(location.getName()).append(",");
                sb.append("address=").append(location.getAddress()).append(",");
                break;

            case TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA:
            case TencentLocationRequest.REQUEST_LEVEL_POI:
            case 7:
                sb.append("nation=").append(location.getNation()).append(",");
                sb.append("province=").append(location.getProvince()).append(",");
                sb.append("city=").append(location.getCity()).append(",");
                sb.append("district=").append(location.getDistrict()).append(",");
                sb.append("town=").append(location.getTown()).append(",");
                sb.append("village=").append(location.getVillage()).append(",");
                sb.append("street=").append(location.getStreet()).append(",");
                sb.append("streetNo=").append(location.getStreetNo()).append(",");

                if (level == TencentLocationRequest.REQUEST_LEVEL_POI) {
                    List<TencentPoi> poiList = location.getPoiList();
                    int size = poiList.size();
                    for (int i = 0, limit = 3; i < limit && i < size; i++) {
                        sb.append("\n");
                        sb.append("poi[" + i + "]=")
                                .append(toString(poiList.get(i))).append(",");
                    }
                }

                break;

            default:
                break;
        }

        return null;
    }

    private static String toString(TencentPoi poi) {
        StringBuilder sb = new StringBuilder();
        sb.append("name=").append(poi.getName()).append(",");
        sb.append("address=").append(poi.getAddress()).append(",");
        sb.append("catalog=").append(poi.getCatalog()).append(",");
        sb.append("distance=").append(poi.getDistance()).append(",");
        sb.append("latitude=").append(poi.getLatitude()).append(",");
        sb.append("longitude=").append(poi.getLongitude()).append(",");
        return sb.toString();
    }
}
